{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "copyright-notice"
   },
   "source": [
    "#### Copyright 2017 Google LLC."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "copyright-notice2"
   },
   "outputs": [],
   "source": [
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zbIgBK-oXHO7"
   },
   "source": [
    " # 特征集"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "bL04rAQwH3pH"
   },
   "source": [
    " **学习目标**：创建一个包含极少特征但效果与更复杂的特征集一样出色的集合"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "F8Hci6tAH3pH"
   },
   "source": [
    " 到目前为止，我们已经将所有特征添加到了模型中。具有较少特征的模型会使用较少的资源，并且更易于维护。我们来看看能否构建这样一种模型：包含极少的住房特征，但效果与使用数据集中所有特征的模型一样出色。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "F5ZjVwK_qOyR"
   },
   "source": [
    " ## 设置\n",
    "\n",
    "和之前一样，我们先加载并准备加利福尼亚州住房数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "SrOYRILAH3pJ"
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "\n",
    "import math\n",
    "\n",
    "from IPython import display\n",
    "from matplotlib import cm\n",
    "from matplotlib import gridspec\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn import metrics\n",
    "import tensorflow as tf\n",
    "from tensorflow.python.data import Dataset\n",
    "\n",
    "tf.logging.set_verbosity(tf.logging.ERROR)\n",
    "pd.options.display.max_rows = 10\n",
    "pd.options.display.float_format = '{:.1f}'.format\n",
    "\n",
    "california_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\", sep=\",\")\n",
    "\n",
    "california_housing_dataframe = california_housing_dataframe.reindex(\n",
    "    np.random.permutation(california_housing_dataframe.index))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "dGnXo7flH3pM"
   },
   "outputs": [],
   "source": [
    "def preprocess_features(california_housing_dataframe):\n",
    "  \"\"\"Prepares input features from California housing data set.\n",
    "\n",
    "  Args:\n",
    "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
    "      from the California housing data set.\n",
    "  Returns:\n",
    "    A DataFrame that contains the features to be used for the model, including\n",
    "    synthetic features.\n",
    "  \"\"\"\n",
    "  selected_features = california_housing_dataframe[\n",
    "    [\"latitude\",\n",
    "     \"longitude\",\n",
    "     \"housing_median_age\",\n",
    "     \"total_rooms\",\n",
    "     \"total_bedrooms\",\n",
    "     \"population\",\n",
    "     \"households\",\n",
    "     \"median_income\"]]\n",
    "  processed_features = selected_features.copy()\n",
    "  # Create a synthetic feature.\n",
    "  processed_features[\"rooms_per_person\"] = (\n",
    "    california_housing_dataframe[\"total_rooms\"] /\n",
    "    california_housing_dataframe[\"population\"])\n",
    "  return processed_features\n",
    "\n",
    "def preprocess_targets(california_housing_dataframe):\n",
    "  \"\"\"Prepares target features (i.e., labels) from California housing data set.\n",
    "\n",
    "  Args:\n",
    "    california_housing_dataframe: A Pandas DataFrame expected to contain data\n",
    "      from the California housing data set.\n",
    "  Returns:\n",
    "    A DataFrame that contains the target feature.\n",
    "  \"\"\"\n",
    "  output_targets = pd.DataFrame()\n",
    "  # Scale the target to be in units of thousands of dollars.\n",
    "  output_targets[\"median_house_value\"] = (\n",
    "    california_housing_dataframe[\"median_house_value\"] / 1000.0)\n",
    "  return output_targets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "jLXC8y4AqsIy"
   },
   "outputs": [],
   "source": [
    "# Choose the first 12000 (out of 17000) examples for training.\n",
    "training_examples = preprocess_features(california_housing_dataframe.head(12000))\n",
    "training_targets = preprocess_targets(california_housing_dataframe.head(12000))\n",
    "\n",
    "# Choose the last 5000 (out of 17000) examples for validation.\n",
    "validation_examples = preprocess_features(california_housing_dataframe.tail(5000))\n",
    "validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n",
    "\n",
    "# Double-check that we've done the right thing.\n",
    "print(\"Training examples summary:\")\n",
    "display.display(training_examples.describe())\n",
    "print(\"Validation examples summary:\")\n",
    "display.display(validation_examples.describe())\n",
    "\n",
    "print(\"Training targets summary:\")\n",
    "display.display(training_targets.describe())\n",
    "print(\"Validation targets summary:\")\n",
    "display.display(validation_targets.describe())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "hLvmkugKLany"
   },
   "source": [
    " ## 任务 1：构建良好的特征集\n",
    "\n",
    "**如果只使用 2 个或 3 个特征，您可以获得的最佳效果是什么？**\n",
    "\n",
    "**相关矩阵**展现了两两比较的相关性，既包括每个特征与目标特征之间的比较，也包括每个特征与其他特征之间的比较。\n",
    "\n",
    "在这里，相关性被定义为[皮尔逊相关系数](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient)。您不必理解具体数学原理也可完成本练习。\n",
    "\n",
    "相关性值具有以下含义：\n",
    "\n",
    "  * `-1.0`：完全负相关\n",
    "  * `0.0`：不相关\n",
    "  * `1.0`：完全正相关"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "test": {
      "output": "ignore",
      "timeout": 600
     }
    },
    "colab_type": "code",
    "id": "UzoZUSdLIolF"
   },
   "outputs": [],
   "source": [
    "correlation_dataframe = training_examples.copy()\n",
    "correlation_dataframe[\"target\"] = training_targets[\"median_house_value\"]\n",
    "\n",
    "correlation_dataframe.corr()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RQpktkNpia2P"
   },
   "source": [
    " 理想情况下，我们希望具有与目标密切相关的特征。\n",
    "\n",
    "此外，我们还希望有一些相互之间的相关性不太密切的特征，以便它们添加独立信息。\n",
    "\n",
    "利用这些信息来尝试移除特征。您也可以尝试构建其他合成特征，例如两个原始特征的比例。\n",
    "\n",
    "为方便起见，我们已经添加了前一个练习的训练代码。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "bjR5jWpFr2xs"
   },
   "outputs": [],
   "source": [
    "def construct_feature_columns(input_features):\n",
    "  \"\"\"Construct the TensorFlow Feature Columns.\n",
    "\n",
    "  Args:\n",
    "    input_features: The names of the numerical input features to use.\n",
    "  Returns:\n",
    "    A set of feature columns\n",
    "  \"\"\" \n",
    "  return set([tf.feature_column.numeric_column(my_feature)\n",
    "              for my_feature in input_features])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "jsvKHzRciH9T"
   },
   "outputs": [],
   "source": [
    "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n",
    "    \"\"\"Trains a linear regression model.\n",
    "  \n",
    "    Args:\n",
    "      features: pandas DataFrame of features\n",
    "      targets: pandas DataFrame of targets\n",
    "      batch_size: Size of batches to be passed to the model\n",
    "      shuffle: True or False. Whether to shuffle the data.\n",
    "      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n",
    "    Returns:\n",
    "      Tuple of (features, labels) for next data batch\n",
    "    \"\"\"\n",
    "    \n",
    "    # Convert pandas data into a dict of np arrays.\n",
    "    features = {key:np.array(value) for key,value in dict(features).items()}                                           \n",
    "    \n",
    "    # Construct a dataset, and configure batching/repeating.\n",
    "    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n",
    "    ds = ds.batch(batch_size).repeat(num_epochs)\n",
    "\n",
    "    # Shuffle the data, if specified.\n",
    "    if shuffle:\n",
    "      ds = ds.shuffle(10000)\n",
    "    \n",
    "    # Return the next batch of data.\n",
    "    features, labels = ds.make_one_shot_iterator().get_next()\n",
    "    return features, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "g3kjQV9WH3pb"
   },
   "outputs": [],
   "source": [
    "def train_model(\n",
    "    learning_rate,\n",
    "    steps,\n",
    "    batch_size,\n",
    "    training_examples,\n",
    "    training_targets,\n",
    "    validation_examples,\n",
    "    validation_targets):\n",
    "  \"\"\"Trains a linear regression model.\n",
    "  \n",
    "  In addition to training, this function also prints training progress information,\n",
    "  as well as a plot of the training and validation loss over time.\n",
    "  \n",
    "  Args:\n",
    "    learning_rate: A `float`, the learning rate.\n",
    "    steps: A non-zero `int`, the total number of training steps. A training step\n",
    "      consists of a forward and backward pass using a single batch.\n",
    "    batch_size: A non-zero `int`, the batch size.\n",
    "    training_examples: A `DataFrame` containing one or more columns from\n",
    "      `california_housing_dataframe` to use as input features for training.\n",
    "    training_targets: A `DataFrame` containing exactly one column from\n",
    "      `california_housing_dataframe` to use as target for training.\n",
    "    validation_examples: A `DataFrame` containing one or more columns from\n",
    "      `california_housing_dataframe` to use as input features for validation.\n",
    "    validation_targets: A `DataFrame` containing exactly one column from\n",
    "      `california_housing_dataframe` to use as target for validation.\n",
    "      \n",
    "  Returns:\n",
    "    A `LinearRegressor` object trained on the training data.\n",
    "  \"\"\"\n",
    "\n",
    "  periods = 10\n",
    "  steps_per_period = steps / periods\n",
    "\n",
    "  # Create a linear regressor object.\n",
    "  my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n",
    "  my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n",
    "  linear_regressor = tf.estimator.LinearRegressor(\n",
    "      feature_columns=construct_feature_columns(training_examples),\n",
    "      optimizer=my_optimizer\n",
    "  )\n",
    "    \n",
    "  # Create input functions.\n",
    "  training_input_fn = lambda: my_input_fn(training_examples, \n",
    "                                          training_targets[\"median_house_value\"], \n",
    "                                          batch_size=batch_size)\n",
    "  predict_training_input_fn = lambda: my_input_fn(training_examples, \n",
    "                                                  training_targets[\"median_house_value\"], \n",
    "                                                  num_epochs=1, \n",
    "                                                  shuffle=False)\n",
    "  predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n",
    "                                                    validation_targets[\"median_house_value\"], \n",
    "                                                    num_epochs=1, \n",
    "                                                    shuffle=False)\n",
    "\n",
    "  # Train the model, but do so inside a loop so that we can periodically assess\n",
    "  # loss metrics.\n",
    "  print(\"Training model...\")\n",
    "  print(\"RMSE (on training data):\")\n",
    "  training_rmse = []\n",
    "  validation_rmse = []\n",
    "  for period in range (0, periods):\n",
    "    # Train the model, starting from the prior state.\n",
    "    linear_regressor.train(\n",
    "        input_fn=training_input_fn,\n",
    "        steps=steps_per_period,\n",
    "    )\n",
    "    # Take a break and compute predictions.\n",
    "    training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n",
    "    training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n",
    "    \n",
    "    validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)\n",
    "    validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n",
    "    \n",
    "    # Compute training and validation loss.\n",
    "    training_root_mean_squared_error = math.sqrt(\n",
    "        metrics.mean_squared_error(training_predictions, training_targets))\n",
    "    validation_root_mean_squared_error = math.sqrt(\n",
    "        metrics.mean_squared_error(validation_predictions, validation_targets))\n",
    "    # Occasionally print the current loss.\n",
    "    print(\"  period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n",
    "    # Add the loss metrics from this period to our list.\n",
    "    training_rmse.append(training_root_mean_squared_error)\n",
    "    validation_rmse.append(validation_root_mean_squared_error)\n",
    "  print(\"Model training finished.\")\n",
    "\n",
    "  \n",
    "  # Output a graph of loss metrics over periods.\n",
    "  plt.ylabel(\"RMSE\")\n",
    "  plt.xlabel(\"Periods\")\n",
    "  plt.title(\"Root Mean Squared Error vs. Periods\")\n",
    "  plt.tight_layout()\n",
    "  plt.plot(training_rmse, label=\"training\")\n",
    "  plt.plot(validation_rmse, label=\"validation\")\n",
    "  plt.legend()\n",
    "\n",
    "  return linear_regressor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "varLu7RNH3pf"
   },
   "source": [
    " 花 5 分钟时间来搜索一组效果良好的特征和训练参数。然后查看解决方案，看看我们选择了哪些参数。请谨记，不同的特征可能需要不同的学习参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "DSgUxRIlH3pg"
   },
   "outputs": [],
   "source": [
    "#\n",
    "# Your code here: add your features of choice as a list of quoted strings.\n",
    "#\n",
    "minimal_features = [\n",
    "]\n",
    "\n",
    "assert minimal_features, \"You must select at least one feature!\"\n",
    "\n",
    "minimal_training_examples = training_examples[minimal_features]\n",
    "minimal_validation_examples = validation_examples[minimal_features]\n",
    "\n",
    "#\n",
    "# Don't forget to adjust these parameters.\n",
    "#\n",
    "train_model(\n",
    "    learning_rate=0.001,\n",
    "    steps=500,\n",
    "    batch_size=5,\n",
    "    training_examples=minimal_training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=minimal_validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "IGINhMIJ5Wyt"
   },
   "source": [
    " ### 解决方案\n",
    "\n",
    "点击下方即可查看解决方案。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "BAGoXFPZ5ZE3"
   },
   "outputs": [],
   "source": [
    "minimal_features = [\n",
    "  \"median_income\",\n",
    "  \"latitude\",\n",
    "]\n",
    "\n",
    "minimal_training_examples = training_examples[minimal_features]\n",
    "minimal_validation_examples = validation_examples[minimal_features]\n",
    "\n",
    "_ = train_model(\n",
    "    learning_rate=0.01,\n",
    "    steps=500,\n",
    "    batch_size=5,\n",
    "    training_examples=minimal_training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=minimal_validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RidI9YhKOiY2"
   },
   "source": [
    " ## 任务 2：更好地利用纬度\n",
    "\n",
    "绘制 `latitude` 与 `median_house_value` 的图形后，表明两者确实不存在线性关系。\n",
    "\n",
    "不过，有几个峰值与洛杉矶和旧金山大致相对应。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "test": {
      "output": "ignore",
      "timeout": 600
     }
    },
    "colab_type": "code",
    "id": "hfGUKj2IR_F1"
   },
   "outputs": [],
   "source": [
    "plt.scatter(training_examples[\"latitude\"], training_targets[\"median_house_value\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6N0p91k2iFCP"
   },
   "source": [
    " **尝试创建一些能够更好地利用纬度的合成特征。**\n",
    "\n",
    "例如，您可以创建某个特征，将 `latitude` 映射到值 `|latitude - 38|`，并将该特征命名为 `distance_from_san_francisco`。\n",
    "\n",
    "或者，您可以将该空间分成 10 个不同的分桶（例如 `latitude_32_to_33`、`latitude_33_to_34` 等）：如果 `latitude` 位于相应分桶范围内，则显示值 `1.0`；如果不在范围内，则显示值 `0.0`。\n",
    "\n",
    "使用相关矩阵来指导您构建合成特征；如果您发现效果还不错的合成特征，可以将其添加到您的模型中。\n",
    "\n",
    "您可以获得的最佳验证效果是什么？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "wduJ2B28yMFl"
   },
   "outputs": [],
   "source": [
    "#\n",
    "# YOUR CODE HERE: Train on a new data set that includes synthetic features based on latitude.\n",
    "#"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "pZa8miwu6_tQ"
   },
   "source": [
    " ### 解决方案\n",
    "\n",
    "点击下方即可查看解决方案。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "PzABdyjq7IZU"
   },
   "source": [
    " 除了 `latitude` 之外，我们还会保留 `median_income`，以便与之前的结果进行比较。\n",
    "\n",
    "我们决定对纬度进行分桶。在 Pandas 中使用 `Series.apply` 执行此操作相当简单。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "xdVF8siZ7Lup"
   },
   "outputs": [],
   "source": [
    "LATITUDE_RANGES = zip(range(32, 44), range(33, 45))\n",
    "\n",
    "def select_and_transform_features(source_df):\n",
    "  selected_examples = pd.DataFrame()\n",
    "  selected_examples[\"median_income\"] = source_df[\"median_income\"]\n",
    "  for r in LATITUDE_RANGES:\n",
    "    selected_examples[\"latitude_%d_to_%d\" % r] = source_df[\"latitude\"].apply(\n",
    "      lambda l: 1.0 if l >= r[0] and l < r[1] else 0.0)\n",
    "  return selected_examples\n",
    "\n",
    "selected_training_examples = select_and_transform_features(training_examples)\n",
    "selected_validation_examples = select_and_transform_features(validation_examples)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "U4iAdY6t7Pkh"
   },
   "outputs": [],
   "source": [
    "_ = train_model(\n",
    "    learning_rate=0.01,\n",
    "    steps=500,\n",
    "    batch_size=5,\n",
    "    training_examples=selected_training_examples,\n",
    "    training_targets=training_targets,\n",
    "    validation_examples=selected_validation_examples,\n",
    "    validation_targets=validation_targets)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "IGINhMIJ5Wyt",
    "pZa8miwu6_tQ",
    "copyright-notice"
   ],
   "default_view": {},
   "name": "feature_sets.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
